/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.asynctasks;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.jaal.movilconsultanet.Progreso;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.XMLContent;
import com.jaal.movilconsultanet.activities.Consulta;

public class GSMSessionRestorer extends AsyncTask<String, Progreso, Boolean> {

	Activity mainActivity;
	ProgressDialog progreso;
	Progreso progresoInfo = new Progreso();
	private String mobileId = null;
	String numero, password, codTlf;

	public GSMSessionRestorer(Activity mainActivity) {
		this.mainActivity = mainActivity;
	}

	@Override
	protected void onPreExecute() {

		progreso = new ProgressDialog(mainActivity);
		progreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progreso.setProgress(0);
		progreso.setMessage(mainActivity.getResources().getText(R.string.connection_connecting_server));
		progreso.setCancelable(false);
		progreso.show();
	}


	@Override
	protected Boolean doInBackground(String... urls) {

		Log.d("MCN", "GSMSessionRestorer - inicio");
		// le paso el captcha cuando hago claseAsync.execute(captcha)
		HttpURLConnection connection = null;

		progresoInfo.setProgreso(10);
		progresoInfo.setMensaje(mainActivity,R.string.connection_prepare);
		publishProgress(progresoInfo);

		URL url;
		String targetURL;
		String urlParameters;

		try {

			mobileId = obtenerMobileId();

			// ahora si me dispongo a hacer el inicio de sesion
			// Create connection
			targetURL = "http://www.movilnet.com.ve/agl/gsm/login.action";
			url = new URL(targetURL);
			Log.d("MCN", "GSMSessionRestorer - conectando..." + targetURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type",
			"application/x-www-form-urlencoded");
			urlParameters = mobileId;
			Log.d("MCN", "GSMSessionRestorer - GSMMobileIdParameter: "
					+ urlParameters);

			connection.setRequestProperty("Content-Length",
					"" + Integer.toString(urlParameters.getBytes().length));
			connection.setRequestProperty("Content-Language", "es-VE");

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			connection.setConnectTimeout(5000);

			Log.d("MCN", "GSMSessionRestorer - sending request");

			progresoInfo.setProgreso(75);
			progresoInfo.setMensaje(mainActivity,R.string.session_restoring);
			publishProgress(progresoInfo);

			// Send request
			DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			Log.d("MCN", "GSMSessionRestorer - NEW connection sessionCookie: "
					+ connection.getHeaderField(3));
			// tomo una nueva sesion para el gsm
			String sessionCookie = connection.getHeaderField(3);

			//			Log.d("MCN",
			//					"GSMSessionRestorer - NEW sessionCookie: "
			//					+ sessionCookie.getSessionCookie());

			progresoInfo.setProgreso(85);
			progresoInfo.setMensaje(mainActivity,R.string.session_restored);
			publishProgress(progresoInfo);

			//			sessionCookie.setGSMSessionStarted(true);

			progresoInfo.setProgreso(95);
			progresoInfo.setMensaje(mainActivity,R.string.configuration_saving);
			publishProgress(progresoInfo);
			// para generar el xml y guardar los datos de la sesion
			String contenido = "sesiones";


			Map<String, String> data = XMLContent.getXML(contenido);

			// guardo el session id DEFINITIVO
			data.put("session_id", sessionCookie);
			data.put("session_started","true");

			//			data.put("session_started",
			//					sessionCookie.isGSMSessionStarted() ? "true" : "false");

			XMLContent.saveXML(contenido, data);

			Log.d("MCN", "getGSMSession - data saved: " + data);

			progresoInfo.setProgreso(100);
			progresoInfo.setFinished(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_final);
			publishProgress(progresoInfo);

			Log.d("MCN", "startSession - fin");

		} catch (ConnectException e) {
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error);
			publishProgress(progresoInfo);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo
			.setMensaje(mainActivity,R.string.connection_error_server);
			publishProgress(progresoInfo);
		} catch (IOException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_io);
			publishProgress(progresoInfo);
		} finally {
			if (connection != null) {
				Log.d("MCN", "getGSMSession - desconectando...");
				connection.disconnect();
			}
		}
		return true;
	}

	@Override
	protected void onProgressUpdate(Progreso... values) {

		Progreso mProgresoInfo = values[0];

		if (!mProgresoInfo.isError()) {
			progreso.setProgress(mProgresoInfo.getProgreso());
			progreso.setMessage(mProgresoInfo.getMensaje());

			if (mProgresoInfo.isFinished()) {
				progreso.dismiss();
			}

		} else {
			progreso.dismiss();
			Toast.makeText(mainActivity, mProgresoInfo.getMensaje(),
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onPostExecute(Boolean result) {

		if (progresoInfo.isError()) {
			return;
		}
		
		if(!mainActivity.getClass().equals(Consulta.class)){
			Intent i = new Intent(mainActivity, Consulta.class);
			mainActivity.startActivity(i);
		}
	}

	public String obtenerMobileId() {
		Map<String, String> mapa = XMLContent.getXML("sesiones");

		String mobileId = null;
		if (mapa != null) {
			mobileId = mapa.get("mobile_id");
		}
		return mobileId;
	}

}
